package core;

import gitobject.GitObject;
import repository.Repository;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class JitCheckout {
    static String branchFilePath = Repository.getGitDir()+ File.separator+"refs"+File.separator+"heads";

    /**
     * Switch to branch.
     * @throws Exception
     */
    public static void switchBranch(String branch) throws Exception {
        if (JitBranch.branchExists(branch)) {
            // switch to branch
            overwriteHEAD(branch);
            // recover worktree
            String commitId = GitObject.getValue(new File(branchFilePath+File.separator+branch));
            JitReset.resetWorkDir(commitId);
        }
        else { // branch not exists
            // create branch & switch to branch
            JitBranch.createBranch(branch);
            overwriteHEAD(branch);
        }
    }

    /**
     * Overwrite HEAD file to current branch.
     * @throws IOException
     */
    public static void overwriteHEAD(String branch) throws IOException {
        File HEAD = new File(Repository.getGitDir() + File.separator + "HEAD");
        FileWriter fw = new FileWriter(HEAD, false);
        fw.write("ref: refs" + File.separator+"heads" + File.separator + branch + "\n");
        fw.close();
    }
}
